<template>
  <div>
    <bcd-top title="支付" englishtitle="ARTICLE CENTER" />
    <template v-if="!$store.getters.screenWidth">
      <div>
        <!-- //收货地址 -->
        <div class="pay">
          <div class="payTitle" style="margin-top:10px">
            <div>请选择收货地址</div>
            <div v-if="showData.length == 0">
              <el-button
                type="primary"
                size="mini"
                style="margin-left:10px;"
                @click="goaddrsss"
              >新增收货地址</el-button>
            </div>
          </div>
          <div class="address">
            <div
              class="addressBox"
              v-for="(item,index) in showData"
              :key="index"
              :style="activeIndex == index ? 'border-color:#3a8ee6' : '' "
              @click="chooseIndex(index,item)"
            >
              <div class="defaultAddress" v-if="item.type == 1">默认地址</div>
              <div class="addressBoxTitle">{{item.province}}({{item.realName}}收)</div>
              <div class="addressBoxDetail">{{item.detail}} {{item.telphone}}</div>
            </div>
            <!-- <div class="allDddress" v-if="showData.length>=4"  @click="allAddres">{{isshowll ? '折叠全部地址' : '示全部地址'}}</div> -->
          </div>
          <div class="payTitle" style="margin-top:20px;">确认订单信息</div>
          <div class="Order">
            <div class="orderLine">商品名称</div>
            <div class="orderLine">商品图片</div>
            <div class="orderLine">规格</div>
            <div class="orderLine">单价</div>
            <div class="orderLine">数量</div>
            <div class="orderLine">小计</div>
          </div>
          <div class="orderInfo" v-for="(item,index) in orderGoodsArr" :key="index">
            <div class="orderLineInfo">{{item && item.product.storeName}}</div>
            <div class="orderLineInfo">
              <img :src=" item && item.product.image" style="width:60px;height:60px" alt />
            </div>
            <div class="orderLineInfo">{{item && item.specObj ? item.specObj.attrs[0].values.join(',') : '暂无'}}</div>
            <div class="orderLineInfo">{{ item && item.specObj ? item.specObj.attrs[0].price : item.product.price}}元</div>
            <div class="orderLineInfo">{{item.cartNum}}</div>
            <div
              class="orderLineInfo"
              style="    font-weight: bold;
    font-style: normal;
    text-decoration: none;
    color: rgb(255, 0, 54);
    font-size: 14px;"
            >{{Number(item && item.specObj ? item.specObj.attrs[0].price : item.product.price) * Number(item.cartNum).toFixed(2)}}元</div>
          </div>
          <div class="payTitle" style="margin-top:20px;margin-bottom:10px">请填写备注</div>
          <el-input type="textarea" :rows="2" placeholder="请填写订单备注" v-model="textarea"></el-input>
          <!-- //支付方式 -->
          <div class="payWay">
            <el-radio-group v-model="payWay" size="mini">
              <el-radio label="weixin" border>微信</el-radio>
              <el-radio label="alipay" border>支付宝</el-radio>
            </el-radio-group>
          </div>
          <!-- 提交订单 -->
          <div class="submitOrder">
            <div class="submitBox">
              <div class="boxsHow">
                <div style="display:flex;align-items:center;margin-top:10px">
                  <div style="font-weight:700;color:#333">实付款:</div>
                  <div style="font-weight:700; color: rgb(255, 0, 54);font-size:26px">￥{{paypaice.toFixed(2)}}</div>
                </div>
                <div style="display:flex;margin-top:10px">
                  <div style="font-weight:700;color:#333">寄送至:</div>
                  <div
                    style="max-width:200px; word-break: break-all;overflow: hidden; text-align: left;"
                  >{{addressObj && addressObj.detail}}</div>
                </div>
                <div style="display:flex;">
                  <div style="font-weight:700;color:#333">收货人:</div>
                  <div
                    style="max-width:200px; word-break: break-all;overflow: hidden;"
                  >{{addressObj && addressObj.realName}}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="submitOrder">
            <el-button type="danger" :loading="orderLoading" @click="creatOrder">提交订单</el-button>
          </div>
        </div>
      </div>
      <footer-part></footer-part>
      <el-dialog
        title="请扫码付款"
        :destroy-on-close="true"
        :show-close="false"
        :visible.sync="dialogVisible"
        width="300px"
      >
        <div>
          <div>{{payWay == 'weixin' ? '请使用微信扫码付款' : "请使用支付宝扫码付款"}}</div>
          <vue-qr :text="payUrl" :size="240"></vue-qr>
        </div>
      </el-dialog>
    </template>
    <template v-else>
      <div>
        <!-- //收货地址 -->
        <div class="pay" style="padding:0px">
          <div class="payTitle" style="margin-top:10px">
            <div>请选择收货地址</div>
            <div v-if="showData.length == 0">
              <el-button
                type="primary"
                size="mini"
                style="margin-left:10px;"
                @click="goaddrsss"
              >新增收货地址</el-button>
            </div>
          </div>
          <div class="address">
            <div
              class="addressBox"
              v-for="(item,index) in showData"
              :key="index"
              style="width:100%"
              :style="activeIndex == index ? 'border-color:#3a8ee6' : '' "
              @click="chooseIndex(index,item)"
            >
              <div class="defaultAddress" v-if="item.type == 1">默认地址</div>
              <div class="addressBoxTitle">{{item.province}}({{item.realName}}收)</div>
              <div class="addressBoxDetail">{{item.detail}} {{item.telphone}}</div>
            </div>
            <!-- <div class="allDddress" @click="allAddres">{{isshowll ? '折叠全部地址' : '展示全部地址'}}</div> -->
          </div>
          <div class="payTitle" style="margin-top:20px;">确认订单信息</div>
          <div class="Order">
            <div class="orderLine">商品名称</div>
            <div class="orderLine">商品图片</div>
            <div class="orderLine">规格</div>
            <div class="orderLine">单价</div>
            <div class="orderLine">数量</div>
            <div class="orderLine">小计</div>
          </div>
          <div class="orderInfo" v-for="(item,index) in orderGoodsArr" :key="index">
            <div class="orderLineInfo">{{item && item.product.storeName}}</div>
            <div class="orderLineInfo">
              <img :src=" item && item.product.image" style="width:60px;height:60px" alt />
            </div>
            <div class="orderLineInfo">{{item && item.specObj ? item.specObj.attrs[0].values.join(',') : '暂无'}}</div>
            <div class="orderLineInfo">{{ item && item.specObj ? item.specObj.attrs[0].price : item.product.price}}元</div>
            <div class="orderLineInfo">{{item.cartNum}}</div>
            <div
              class="orderLineInfo"
              style="    font-weight: bold;
    font-style: normal;
    text-decoration: none;
    color: rgb(255, 0, 54);
    font-size: 14px;"
            >{{Number(item && (item.specObj ? item.specObj.attrs[0].price : item.product.price)) * Number(item.cartNum).toFixed(2)}}元</div>
          </div>
          <div class="payTitle" style="margin-top:20px;margin-bottom:10px">请填写备注</div>
          <el-input type="textarea" :rows="2" placeholder="请填写订单备注" v-model="textarea"></el-input>
          <!-- //支付方式 -->
          <div class="payWay">
            <el-radio-group v-model="payWay" size="mini">
              <el-radio label="weixin" border>微信</el-radio>
              <el-radio label="alipay" border>支付宝</el-radio>
            </el-radio-group>
          </div>
          <!-- 提交订单 -->
          <div class="submitOrder">
            <div class="submitBox">
              <div class="boxsHow">
                <div style="display:flex;align-items:center;margin-top:10px">
                  <div style="font-weight:700;color:#333">实付款:</div>
                  <div style="font-weight:700; color: rgb(255, 0, 54);font-size:26px">￥{{paypaice.toFixed(2)}}</div>
                </div>
                <div style="display:flex;margin-top:10px">
                  <div style="font-weight:700;color:#333">寄送至:</div>
                  <div
                    style="max-width:200px; word-break: break-all;overflow: hidden; text-align: left;"
                  >{{addressObj && addressObj.detail}}</div>
                </div>
                <div style="display:flex;">
                  <div style="font-weight:700;color:#333">收货人:</div>
                  <div
                    style="max-width:200px; word-break: break-all;overflow: hidden;"
                  >{{addressObj && addressObj.realName}}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="submitOrder">
            <el-button type="danger" :loading="orderLoading" @click="creatOrderbyWEIXIN">提交订单</el-button>
          </div>
        </div>
      </div>
      <footer-part></footer-part>
    </template>
  </div>
</template>

<script>
import {
  addressAdd,
  addressList,
  setDefault,
  aliunifiedorder,
  createOrderAlipay
} from "@/api/api.js";
import vueQr from "vue-qr";
import footerPart from "../views/footer";
import bcdTop from "../components/bcdTop";
import ap from "./ap";
import {
  productDetail,
  addCart,
  buyNow,
  orderAdd,
  unifiedorder,
  statusPay,
  prepay
} from "../api/api";
export default {
  name: "pay",
  components: {
    footerPart,
    bcdTop,
    vueQr
  },
  beforeDestroy() {
    clearInterval(this.inter);
  },
  data() {
    return {
      dialogTableVisible: true,
      tableData: [],
      activeIndex: 0,
      addressObj: null,
      isshowll: false,
      pInfo: null, //产品详情
      proId: null,
      cartNum: null,
      payWay: "weixin",
      orderLoading: false,
      cartIds: null,
      payUrl: null,
      dialogVisible: false,
      inter: null,
      textarea: null,
      orderGoodsArr: [],
      paypaice: null,
      orderId: null
    };
  },
  watch: {
    payWay() {
      this.payUrl = null;
    }
  },
  computed: {
    showData() {
      // if (this.isshowll) {
      return this.tableData;
      // } else {
      //   return this.tableData.slice(0, 4);
      // }
    }
  },
  mounted() {

this.orderGoodsArr = JSON.parse(this.$route.query.paArr);
      console.log("11111111111",this.orderGoodsArr)

    let arr = [];
    let price = 0;
    let cartNum = 0;
    this.orderGoodsArr &&
      this.orderGoodsArr.forEach(e => {
        arr.push(e.id);
        price = price + Number(e.specObj ? e.specObj.attrs[0].price : e.product.price) * Number(e.cartNum).toFixed(2);
        cartNum = cartNum + e.cartNum;
      });
    this.cartIds = arr.join(",");
    this.paypaice = price;
    this.cartNum = cartNum;
    // return;
    // this.proId = this.$route.query.id;
    // this.cartNum = this.$route.query.num;
    // this.cartIds = this.$route.query.cartIds;
    this.getListAddres();
    this.getinfo();
  },
  methods: {
    // closeDia() {
    //   clearInterval(this.inter);
    // },
    chooseIndex(index, item) {
      this.activeIndex = index;
      this.addressObj = item;
    },
    allAddres() {
      this.isshowll = !this.isshowll;
    },
    alipay_H5(data) {
      const div = document.createElement("div");
      div.innerHTML = data;
      document.body.appendChild(div);
      //document.forms.alipaysubmit.submit();

      var queryParam = "";

      Array.prototype.slice
        .call(document.querySelectorAll("input[type=hidden]"))
        .forEach(function(ele) {
          queryParam += "&" + ele.name + "=" + encodeURIComponent(ele.value);
        });
      var gotoUrl = document.forms.punchout_form.action+queryParam;
      _AP.pay(gotoUrl);
    },
    async getinfo() {
      let info = await productDetail({ id: this.proId });
      this.pInfo = info.data;
    },
    async getListAddres() {
      const { data } = await addressList({
        uid: this.$store.getters["userId"]
      });
      this.tableData = data;
      data.forEach((e, index) => {
        if (e.type == 1) {
          this.addressObj = e;
          this.activeIndex = index;
        }
      });
    },

    async creatOrderbyWEIXIN() {
      if (this.tableData.length == 0) {
        setTimeout(() => {
          this.$notify({
            title: "请先添加收货地址",
            type: "error"
          });
        }, 500);
        return;
      }
      this.orderLoading = true;

      const { data } = await orderAdd({
        cartIds: this.cartIds,
        couponId: null,
        couponPrice: null,
        deductionPrice: null,
        expressDump: null,
        freightFree: 0,
        mark: this.textarea,
        payPostage: 0,
        payPrice: this.paypaice,
        province: this.addressObj.province,
        realName: this.addressObj.realName,
        totalNum: this.cartNum,
        totalPostage: 0,
        totalPrice: this.paypaice,
        uid: this.$store.getters["userId"],
        userAddress: this.addressObj.detail,
        userPhone: this.addressObj.telphone
      });
      window.sessionStorage.getItem("openId");

      this.orderLoading = false;

      if (this.payWay == "alipay") {
        const alires = await createOrderAlipay({
          id: data
        });
        this.alipay_H5(alires.data.form);
        this.inter = setInterval(() => {
        statusPay({
          id: data
        }).then(res => {
          if (res.data.paid == 1) {
            clearInterval(this.inter);
            this.$notify({
              title: "支付成功！",
              type: "success"
            });
            this.payUrl = null;
            setTimeout(() => {
              this.$router.push("/mineCenter");
            }, 500);
          }
        });
      }, 3000);
      setTimeout(() => {
        clearInterval(this.inter);
      }, 900000);
      } else {
        const res = await prepay({
          id: data,
          openId: window.sessionStorage.getItem("openId")
        });
        WeixinJSBridge.invoke(
          "getBrandWCPayRequest",
          {
            appId: res.data.appId, //公众号ID，由商户传入
            timeStamp: res.data.timeStamp, //时间戳，自1970年以来的秒数
            nonceStr: res.data.nonceStr, //随机串
            package: res.data.prepayId,
            signType: res.data.signType, //微信签名方式：
            paySign: res.data.paySign //微信签名
          },
          res => {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              this.$notify({
                title: "支付成功！",
                type: "success"
              });
              this.$router.push("/mineCenter");
            }
            if (res.err_msg == "get_brand_wcpay_request:fail") {
              this.$notify({
                title: "支付失败！",
                type: "success"
              });
              this.$router.push("/mineCenter");
            }
          }
        );
      }
    },
    goaddrsss() {
      this.$router.push("/address");
    },
    async creatOrder() {
      //判断是否有地址
      if (this.tableData.length == 0) {
        setTimeout(() => {
          this.$notify({
            title: "请先添加收货地址",
            type: "error"
          });
        }, 500);
        return;
      }
      this.orderLoading = true;
      if (this.payUrl) {
      } else {
        const { data } = await orderAdd({
          cartIds: this.cartIds,
          couponId: null,
          couponPrice: null,
          deductionPrice: null,
          expressDump: null,
          freightFree: 0,
          mark: this.textarea,
          payPostage: 0,
          payPrice: this.paypaice,
          province: this.addressObj.province,
          realName: this.addressObj.realName,
          totalNum: this.cartNum,
          totalPostage: 0,
          totalPrice: this.paypaice,
          uid: this.$store.getters["userId"],
          userAddress: this.addressObj.detail,
          userPhone: this.addressObj.telphone
        });
        this.orderId = data;
        if (this.payWay == "weixin") {
          const urlPay = await unifiedorder({
            id: this.orderId
          });
          this.payUrl = urlPay.data.code_url;
        }
        if (this.payWay == "alipay") {
          const urlPay = await aliunifiedorder({
            id: this.orderId
          });
          this.payUrl = urlPay.data.code_url;
        }
      }

      this.orderLoading = false;
      this.dialogVisible = true;
      this.inter = setInterval(() => {
        statusPay({
          id: this.orderId
        }).then(res => {
          if (res.data.paid == 1) {
            clearInterval(this.inter);
            this.$notify({
              title: "支付成功！",
              type: "success"
            });
            this.payUrl = null;
            setTimeout(() => {
              this.$router.push("/mineCenter");
            }, 500);
          }
        });
      }, 3000);
      setTimeout(() => {
        clearInterval(this.inter);
      }, 900000);
    }
  }
};
</script>

<style lang='scss'>
.pay {
  padding: 20px;
  width: 90%;
  margin: 0 auto;
  .payTitle {
    line-height: 25px;
    color: #333;
    font-weight: 700;
    font-size: 14px;
    text-align: left;
    display: flex;
    align-items: center;
  }
  .orderInfo {
    display: flex;
    width: 100%;
    margin-top: 10px;
    justify-content: space-between;
    background-color: rgb(242, 247, 255);
    border-bottom: 1px dotted rgb(128, 178, 255);
    border-top: 1px dotted rgb(128, 178, 255);
    .orderLineInfo {
      width: 19%;
      height: 70px;
      word-break: break-all;
      overflow: hidden;

      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .submitOrder {
    width: 100%;
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
    .submitBox {
      border: 1px solid #ff0036;
      .boxsHow {
        border: 3px solid #fff0e8;
        min-width: 230px;
        padding: 10px 5px 10px 20px;
      }
    }
  }
  .payWay {
    width: 100%;
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  .Order {
    display: flex;
    width: 100%;
    margin-top: 30px;
    justify-content: space-between;
    .orderLine {
      width: 19%;
      height: 24px;
      line-height: 24px;
      text-align: center;
      border-bottom: 3px solid #b2d1ff;
      font-size: 12px;
      margin-left: 1px;
      vertical-align: bottom;
    }
  }
  .address {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;
    .addressBox {
      width: 22%;
      min-height: 50px;
      margin-right: 20px;
      border: 1px solid #ccc;
      margin-bottom: 10px;
      padding: 10px;
      position: relative;
      cursor: pointer;
      .defaultAddress {
        position: absolute;
        top: 0;
        right: 0;
        background: #ccc;
        color: #fff;
        padding: 0 2px;
        text-decoration: none;
        opacity: 0.7;
      }
      .addressBoxTitle {
        text-align: left;
        width: 100%;
        border-bottom: 1px solid #f2f2f2;
        padding: 0 0 5px;
        margin-bottom: 5px;
        line-height: 18px;
        font-weight: 700;
      }
      .addressBoxDetail {
        text-align: left;
      }

      &:hover {
        border-color: #3a8ee6;
      }
      & + .addressBox {
      }
    }
    .allDddress {
      text-align: left;
      color: #c97;
      cursor: pointer;
    }
  }
}
</style>